package com.cskaoyan.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

/**
 * @author stone
 * @date 2022/10/04 20:55
 */
@Aspect
@Component
public class TransactionAspect {

    @Autowired
    PlatformTransactionManager transactionManager;

    @Around("@annotation(com.cskaoyan.annotation.WdTransaction)")
    public Object transactionAround(ProceedingJoinPoint joinPoint) {
        TransactionStatus status = transactionManager.getTransaction(TransactionDefinition.withDefaults());
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            //throwable.printStackTrace();
            transactionManager.rollback(status);
        }
        transactionManager.commit(status);
        return proceed;
    }
}
